/**
 * @file drv_spi.c
 * @brief 
 * 
 * @author dalin (dalin@open-robot.com)
 * @version 1.0
 * @date 2023-05-11
 * 
 * @copyright Copyright (c) 2023  Open Robot Tech.co, Ltd
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2023-05-11 <td>1.0     <td>dalin     <td>创建驱动文件
 * <tr><td>2023-06-02 <td>1.1     <td>dalin     <td>创建阻塞收发接口
 * </table>
 */

#include "drv_spi.h"
#ifdef USE_SPI_DRIVER

__weak SPI_HandleTypeDef hspi1;
__weak SPI_HandleTypeDef hspi2;
__weak SPI_HandleTypeDef hspi3;


static SPI_HandleTypeDef* get_spi_handle(spiNumber_e spi)
{
    if(spi == DRV_SPI1)
        return &hspi1;
    else if(spi == DRV_SPI2)
        return &hspi2;
    else if(spi == DRV_SPI3)
        return &hspi3;
}


/**
 * @brief SPI发送数据
 * 
 * @param  drv              : spi设备
 * @param  data             : 数据缓存区
 * @param  len              : 数据长度
 * @param  timeout          : 超时时间
 * 
 * @return int 
 */
int drv_spi_send(spiDrv_t drv, uint8_t * data, uint16_t len, uint32_t timeout)
{
    SPI_HandleTypeDef *hspi =NULL;
    int ret;

    hspi = get_spi_handle(drv.hspi);

    /* 如果使用软件CS */
    if(drv.hw_cs != NULL)
        drv_gpio_write(drv.hw_cs, DRV_PIN_LOW);

    if(HAL_SPI_Transmit(hspi, data, len, timeout) != HAL_OK)
    {
        ret =  DRV_ERROR;
    }
    else
        ret =  HAL_OK;

    if(drv.hw_cs != NULL)
        drv_gpio_write(drv.hw_cs, DRV_PIN_HIGH);

    return ret;
}


/**
 * @brief SPI接收数据
 * 
 * @param  drv              : spi设备
 * @param  data             : 数据缓存区
 * @param  len              : 数据长度
 * @param  timeout          : 超时时间
 * 
 * @return int 
 */
int drv_spi_read(spiDrv_t drv, uint8_t * data, uint16_t len, uint32_t timeout)
{
    SPI_HandleTypeDef *hspi =NULL;
    int ret;

    hspi = get_spi_handle(drv.hspi);

    /* 如果使用软件CS */
    if(drv.hw_cs != NULL)
        drv_gpio_write(drv.hw_cs, DRV_PIN_LOW);

    if(HAL_SPI_Receive(hspi, data, len, timeout) != HAL_OK)
    {
        ret =  DRV_ERROR;
    }
    else
        ret =  HAL_OK;

    if(drv.hw_cs != NULL)
        drv_gpio_write(drv.hw_cs, DRV_PIN_HIGH);

    return ret;
}


/**
 * @brief SPI 收发
 * 
 * @param  tx_data          : 数据接收缓存区
 * @param  rx_data          : 数据发送缓存区
 * @param  len              : 数据长度
 * @param  timeout          : 超时时间
 * 
 * @return int 
 */
int drv_spi_transfer(struct drv_spi, uint8_t * tx_data, uint8_t * rx_data, uint16_t len, uint32_t timeout)
{
    SPI_HandleTypeDef *hspi =NULL;
    int ret;

    hspi = get_spi_handle(drv.hspi);

    /* 如果使用软件CS */
    if(drv.hw_cs != NULL)
        drv_gpio_write(drv.hw_cs, DRV_PIN_LOW);

    if(HAL_SPI_Receive(hspi, tx_data, rx_data, len, timeout) != HAL_OK)
    {
        ret =  DRV_ERROR;
    }
    else
        ret =  HAL_OK;

    if(drv.hw_cs != NULL)
        drv_gpio_write(drv.hw_cs, DRV_PIN_HIGH);

    return ret;
}

#endif /* USE_SPI_DRIVER */
